package com.emar.adx.yiqifa.util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by xiaoliang
 * 2016.11.21 17:34
 *
 * @Version 1.0
 */
public class HikariCPPoolUtil {
    private static final Logger logger = LoggerFactory.getLogger(HikariCPPoolUtil.class);

    private static DataSource ds;

    /**
     * 初始化连接池代码块
     */
    static {
        initDBSource();
    }

    /**
     * 初始化c3p0连接池
     */
    private static final void initDBSource() {
        Properties properties = new Properties();
        try {
            // 加载配置文件
            properties.load(FileUtils.getFileInputStream("config/hikari.properties"));
        } catch (Exception e) {
            logger.error("error : ",e);
        }
        HikariConfig config = new HikariConfig(properties);
        ds = new HikariDataSource(config);
    }

    /**
     * 获取数据库连接对象
     *
     * @return 数据连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        final Connection conn = ds.getConnection();
//        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return conn;
    }

    public static void closeConnection(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("close connection error : ",e);
            }
        }
    }

    public static void closePreparedStatement(PreparedStatement pre){
        if(pre!=null){
            try {
                pre.close();
            } catch (SQLException e) {
                logger.error("close PreparedStatement error : ",e);
            }
        }
    }

    public static void closePool() {
        HikariDataSource h = (HikariDataSource) ds;
        h.close();
    }
}
